package com.example.webdemo.config;

import com.example.webdemo.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    private final LoginInterceptor loginInterceptor;

    // 自动注入拦截器（关键！）
    @Autowired
    public MyWebConfig(LoginInterceptor loginInterceptor) {
        this.loginInterceptor = loginInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/login",              // 登录页面
                        "/login/login",        // 登录API
                        "/register",            // 注册路径
                        "/user/register",
                        "/user",
                        "/logout",             // 注销路径
                        "/reset-password",     // 重置密码
                        "/css/**",
                        "/js/**",
                        "/images/**",
                        "/fonts/**",
                        "/error",              // 错误页面
                        "/registration.html"
                );
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}